import { Card as SemiCard, ButtonGroup, Button } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh, IconDelete } from "@douyinfe/semi-icons";
import { useEffect, useState } from "react";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { Avatar, Card, List, message, Popconfirm, Row, Col, Spin, Space, Select, Cascader, Descriptions, Typography } from "antd";

import useStaff from "../hooks/staff/useStaff";
import useGlobalSetting from "../hooks/globalSetting/useGlobalSetting";
import useUpdateGlobalSetting from "../hooks/globalSetting/useUpdateGlobalSetting";
import useAreaCode from "../hooks/useAreaCode";

const Setting = () => {
    const { windowInnerHeight } = useModel("global");
    const { loading, staffs } = useStaff({ osType: "正式" });
    const { globalSettings, loadGlobalSettings } = useGlobalSetting();
    const { updateGlobalSetting } = useUpdateGlobalSetting();
    const { loadAreaData, areas } = useAreaCode();

    const [selectedArea, setSelectedArea] = useState([]);

    const state = useReactive({
        areas: [],
    });

    useEffect(() => {
        areas.length > 0 && (state.areas = areas);
    }, [areas]);

    useEffect(() => {
        const orgArea = globalSettings["organization-area"] || [];
        if (orgArea.length > 0) {
            let areasCache = globalAreaCode["0"].map((item) => {
                if (item.id === orgArea[0].id) {
                    return {
                        ...item,
                        isLeaf: false,
                        level: 1,
                        children: globalAreaCode[item.id].map((item1) => {
                            if (item1.id === orgArea[1].id) {
                                return {
                                    ...item1,
                                    isLeaf: false,
                                    level: 2,
                                    children: globalAreaCode[item1.id].map((item2) => {
                                        if (item2.id === orgArea[2].id) {
                                            return {
                                                ...item2,
                                                isLeaf: false,
                                                level: 3,
                                                children: globalAreaCode[item2.id].map((item3) => ({ ...item3, isLeaf: true, level: 4 })),
                                            };
                                        }
                                        return { ...item2, isLeaf: false, level: 3 };
                                    }),
                                };
                            }
                            return { ...item1, isLeaf: false, level: 2 };
                        }),
                    };
                }
                return { ...item, isLeaf: false, level: 1 };
            });
            state.areas = areasCache;
        } else {
            state.areas = areas;
        }
    }, [globalSettings]);

    // 设置组织负责人
    const updateOrganizationHead = async (value, record) => {
        if (!value) return;
        let values = {
            gsJson: record,
            gsType: "json",
            gsValue: "",
            gsKey: "organization-head",
        };
        let res = await updateGlobalSetting(values, globalSettings[values.gsKey] ? "update" : "create");
        if (res) {
            message.success("成功设置组织负责人信息");
            loadGlobalSettings(true);
        }
    };

    const updateGlobalKeyValue = async (key, value) => {
        if (!value) return;
        let values = {
            gsJson: {},
            gsType: "string",
            gsValue: value,
            gsKey: key,
        };
        let res = await updateGlobalSetting(values, globalSettings[key] ? "update" : "create");
        if (res) {
            message.success("成功保存设置信息");
            loadGlobalSettings(true);
        }
    };

    const onAreaChange = async (value, selectedOptions) => {
        let values = {
            gsJson: selectedOptions?.map((item) => ({ id: item.id, text: item.text })) || [],
            gsType: "json",
            gsValue: "",
            gsKey: "organization-area",
        };
        // console.log(values);
        // return;
        let res = await updateGlobalSetting(values, globalSettings[values.gsKey] !== undefined ? "update" : "create");
        if (res) {
            message.success("成功保存设置信息");
            loadGlobalSettings(true);
            if (values.gsJson.length === 0) {
                state.areas = areas;
            }
        }
    };

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 48;

    return (
        <div id="setting" style={{ margin: 10 }}>
            <SemiCard
                title={<span style={{ lineHeight: "32px", fontSize: 15 }}> 组织相关设置 </span>}
                headerStyle={{ padding: "7px 12px" }}
                shadows="always"
                bordered={false}
                bodyStyle={{ padding: 0, height: cardBodyHeight }}
            >
                <Space direction="vertical" style={{ padding: 10, width: "100%" }} size={16}>
                    <Card
                        title="组织负责人"
                        size="small"
                        hoverable
                        bordered={false}
                        bodyStyle={{ padding: 0 }}
                        extra={
                            <Space>
                                <div>设置组织负责人：</div>
                                <Select
                                    loading={loading}
                                    allowClear
                                    placeholder="请选择"
                                    fieldNames={{ label: "osName", value: "osUuid" }}
                                    options={staffs?.map(({ osName, osUuid }) => ({ osName, osUuid }))}
                                    style={{ width: 200 }}
                                    onChange={updateOrganizationHead}
                                />
                            </Space>
                        }
                    >
                        <Descriptions column={3} bordered labelStyle={{ width: 140 }} contentStyle={{ width: 640 }}>
                            <Descriptions.Item label="姓名">{globalSettings["organization-head"]?.osName}</Descriptions.Item>
                        </Descriptions>
                    </Card>

                    <Card title="组织办公地点" size="small" hoverable bordered={false} bodyStyle={{ padding: 0 }}>
                        <Descriptions column={2} bordered labelStyle={{ width: 140 }} contentStyle={{ width: 640 }}>
                            <Descriptions.Item label="所在地区">
                                <Cascader
                                    placeholder="请选择"
                                    allowClear
                                    value={globalSettings["organization-area"]?.map((item) => item.id) || []}
                                    options={state.areas}
                                    loadData={loadAreaData}
                                    onChange={onAreaChange}
                                    fieldNames={{ label: "text", value: "id" }}
                                    style={{ width: 500 }}
                                />
                            </Descriptions.Item>

                            <Descriptions.Item label="地图经度">
                                <Typography.Text editable={{ onChange: (value) => updateGlobalKeyValue("organization-map-radius", value) }} style={{ marginBottom: 0 }}>
                                    {globalSettings["organization-map-radius"]}
                                </Typography.Text>
                            </Descriptions.Item>

                            <Descriptions.Item label="详细地址">
                                <Typography.Text editable={{ onChange: (value) => updateGlobalKeyValue("organization-address", value) }} style={{ marginBottom: 0 }}>
                                    {globalSettings["organization-address"]}
                                </Typography.Text>
                            </Descriptions.Item>

                            <Descriptions.Item label="地图纬度">
                                <Typography.Text editable={{ onChange: (value) => updateGlobalKeyValue("organization-map-latitude", value) }} style={{ marginBottom: 0 }}>
                                    {globalSettings["organization-map-latitude"]}
                                </Typography.Text>
                            </Descriptions.Item>
                        </Descriptions>
                    </Card>

                    <Card title="组织代码" size="small" hoverable bordered={false} bodyStyle={{ padding: 0 }}>
                        <Descriptions column={3} bordered labelStyle={{ width: 140 }} contentStyle={{ width: 640 }}>
                            <Descriptions.Item label="社会信用代码">
                                <Typography.Text editable={{ onChange: (value) => updateGlobalKeyValue("organization-social-credit-code", value) }} style={{ marginBottom: 0 }}>
                                    {globalSettings["organization-social-credit-code"]}
                                </Typography.Text>
                            </Descriptions.Item>
                        </Descriptions>
                    </Card>

                    <Card title="税务信息" size="small" hoverable bordered={false} bodyStyle={{ padding: 0 }}>
                        <Descriptions column={3} bordered labelStyle={{ width: 140 }}>
                            <Descriptions.Item label="纳税人识别号">
                                <Typography.Text
                                    editable={{ onChange: (value) => updateGlobalKeyValue("organization-taxpayer-identification-number", value) }}
                                    style={{ marginBottom: 0 }}
                                >
                                    {globalSettings["organization-taxpayer-identification-number"]}
                                </Typography.Text>
                            </Descriptions.Item>
                            <Descriptions.Item label="开户行名称">
                                <Typography.Text editable={{ onChange: (value) => updateGlobalKeyValue("organization-bank-name", value) }} style={{ marginBottom: 0 }}>
                                    {globalSettings["organization-bank-name"]}
                                </Typography.Text>
                            </Descriptions.Item>
                            <Descriptions.Item label="开户行账号">
                                <Typography.Text editable={{ onChange: (value) => updateGlobalKeyValue("organization-bank-account", value) }} style={{ marginBottom: 0 }}>
                                    {globalSettings["organization-bank-account"]}
                                </Typography.Text>
                            </Descriptions.Item>
                        </Descriptions>
                    </Card>
                </Space>
            </SemiCard>
        </div>
    );
};

export default Setting;
